package com.lanzuo.yxd.scanner.conveyor;

import cn.hutool.extra.spring.SpringUtil;
import com.ghgande.j2mod.modbus.Modbus;
import com.lanzuo.yxd.scanner.config.LaneConfig;
import com.lanzuo.yxd.scanner.config.ScannerConfig;
import com.lanzuo.yxd.scanner.config.SpringContextHolder;
import com.lanzuo.yxd.scanner.dto.SubmitResult;
import com.lanzuo.yxd.scanner.scanner.ScanResultHolder;
import com.lanzuo.yxd.scanner.scanner.ScannerClient;
import com.lanzuo.yxd.scanner.scanner.ScannerWaitNotifyCoordinator;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author eric
 * <p>
 * 传感器信号检测器
 * <p>
 * 对接yxd的传感器信号量
 */
@Slf4j
public class SensorSignalListener implements Runnable {
    static final Integer SIGNAL_EXIST = 1;
    static final Integer SLEEP_SECONDS = 3;
    static final Integer MAX_RETRY_COUNTS = 3;
    static final Integer PANEL_OK_SIGNAL = 1;
    static final Integer PANEL_NG_SIGNAL = 2;

    private final LaneConfig laneConfig;
    private final ScannerWaitNotifyCoordinator coordinator;
    private volatile boolean running = true;

    /**
     * sensor listener init
     *
     * @param laneConfig 轨道配置
     */
    public SensorSignalListener(LaneConfig laneConfig) {
        this.laneConfig = laneConfig;
        this.coordinator = SpringUtil.getBean(ScannerWaitNotifyCoordinator.class);
//        this.coordinator = new ScannerWaitNotifyCoordinator();
    }

    public void stop() {
        this.running = false;
    }

    /**
     * 暂停几秒
     */
    private void sleep() {
        try {

            String sleepSeconds = SpringContextHolder.getProperty("loop.duration", SLEEP_SECONDS + "");
            TimeUnit.SECONDS.sleep(Long.parseLong(sleepSeconds));
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // 恢复中断状态
            throw new RuntimeException(e);
        }
    }

    @Override
    public void run() {
        Integer lane = laneConfig.getLaneNo();
        while (running) {
            try {
                // 循环检测传感器信号
                ModbusMaster modbusMaster4R = new ModbusMaster(laneConfig.getIp(), Modbus.DEFAULT_PORT);
                Integer signal = modbusMaster4R.readSignal(laneConfig.getSensorAddress());
                if (signal == null) {
                    log.info("传感器信号量为空，程序出现异常");
                    sleep();
                    continue;
                }

                if (SIGNAL_EXIST.equals(signal)) {
                    SubmitResult result = new SubmitResult(false, 0, "Mes结果异常");
                    log.info("捕获到传感器信号, {}, 准备驱动扫码器扫码！", SIGNAL_EXIST);
                    for (int i = 1; i <= MAX_RETRY_COUNTS; i++) {
                        log.info("[{}]scanner 第{}次扫码", Thread.currentThread().getName(), i);
                        ScannerConfig topScanner = laneConfig.getScanner().stream().filter(v -> "top".equalsIgnoreCase(v.getPosition())).findFirst().orElse(null);
                        ScannerConfig bottomScanner = laneConfig.getScanner().stream().filter(v -> "bottom".equalsIgnoreCase(v.getPosition())).findFirst().orElse(null);

                        // === 扫 top ===
                        if (topScanner != null) {
                            ScanResultHolder topHolder = coordinator.createHolder(lane, topScanner.getIp(), topScanner.getPosition());
                            // 先扫上面的码
                            ScannerClient topClient = new ScannerClient(lane, topScanner.getIp(), topScanner.getPosition());
                            topClient.sendT1();

                            try {
                                // 3秒超时
                                result = topHolder.waitForResult(3000);
                                log.info("Lane-{}-Top 扫码校验结果: {}", lane, result.getSuccess());
                            } catch (TimeoutException e) {
                                log.warn("Lane-{}-Top 扫码校验超时", lane);
                            } finally {
                                topClient.destroy();
                            }
                        }

                        // === 扫 bottom ===
                        if (!result.getSuccess() && bottomScanner != null) {
                            ScanResultHolder bottomHolder = coordinator.createHolder(lane, bottomScanner.getIp(), bottomScanner.getPosition());
                            // 先扫上面的码
                            ScannerClient bottomClient = new ScannerClient(lane, bottomScanner.getIp(), bottomScanner.getPosition());
                            bottomClient.sendT1();

                            try {
                                // 3秒超时
                                result = bottomHolder.waitForResult(3000);
                                log.info("Lane-{}-Bottom 扫码校验结果: {}", lane, result.getSuccess());
                            } catch (TimeoutException e) {
                                log.warn("Lane-{}-Bottom 扫码校验超时", lane);
                            } finally {
                                bottomClient.destroy();
                            }
                        }

                        if (result.getSuccess()) {
                            break;
                        }
                    }

                    ModbusMaster modbusMaster4W = new ModbusMaster(laneConfig.getIp(), Modbus.DEFAULT_PORT);
                    if (result.getSuccess()) {
                        // 开启进板
                        modbusMaster4W.writeSignal(laneConfig.getPanelInAddress(), PANEL_OK_SIGNAL);
                    } else {
                        // 给plc发送提示显示
                        log.info("[MES]接口返回异常，拒绝进板，error msg:{}", result.getMessage());
                        modbusMaster4W.writeSignal(laneConfig.getPanelInAddress(), PANEL_NG_SIGNAL);
                    }
                }

                sleep();
            } catch (Exception e) {
                e.printStackTrace();
                log.error("<SensorSignalListener> 传感器检测异常 error: {}", e.getMessage());
            }
        }
    }

}
